﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class Optional : Pattern
    {
        public Pattern Pattern { get; private set; }
        public Optional(Pattern pattern)
            : base(PatternKind.Optional)
        {
            this.Pattern = pattern;
        }

        public override PatternMatch Compile()
        {
            var p = Pattern.Compile();
            return s => Target(s, p);
        }

        private static async Task<IMatch> Target(IScope scope, PatternMatch pattern)
        {
            var match = await pattern(scope);
            if (match.Matched)
                return match;

            return await Transformation.Match.Default(scope.SetMemos(match.End.Memos));
        }
    }
}
